package com.moon.game.client;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;

import org.apache.log4j.Logger;

import com.moon.game.message.ObjMessage;

/**
 * client的连接池
 * */
public class ClientPoolMulti {
	private static final Logger log = Logger.getLogger(ClientPoolMulti.class);
	private String host;
	private int port;
	private int size;  
	private int type;
	
	private LinkedBlockingQueue<UdpClient> idleQ;
	
	public void initClientPool(String h, int p, int codec, int sendBufferSize, int recvBufferSize, int poolSize)
	{
		host = h;
		port = p;
		size = poolSize;
		
		idleQ = new LinkedBlockingQueue<UdpClient>(size);
		
		for(int i=0; i<size; i++){
			UdpClient client = new UdpClient(host, port, codec, sendBufferSize, recvBufferSize);
			idleQ.add( client );
		}
		log.info("pool init finish：idleQ="+ idleQ.size());
	}
	/**
	 * 初始化连接池
	 * @param h host
	 * @param p port
	 * @param size pool size
	 * @param t abandonedTime
	 * */
	public ClientPoolMulti(String h, int p, int codec, int sendBufferSize, int recvBufferSize, int poolSize)
	{
		initClientPool(h, p,codec, sendBufferSize, recvBufferSize, poolSize);
	}
	/**
	 * 利用空闲连接发,发送后等待应答，收到应答归还连
	 * */
	public void send(ObjMessage msg){
		UdpClient client = null;
		try {
			client = idleQ.poll(100, TimeUnit.MILLISECONDS);
		} catch (InterruptedException e) {
		}

		if(client == null ){
			log.error("idleQ is empty!!!, pool full");
			return;
		}
		try {
			client.send(msg);
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		
		//还回连接池
		try{
			idleQ.add(client);
		}
		catch(Exception e){
			log.error("exception", e);
		}
	}
	
	
	public int getIdleNum(){
		return idleQ.size();
	}
}
